import Toast from '@vant/weapp/toast/toast';

const app = getApp();

Page({
    /**
     * 页面的初始数据
     */
    data: {
        productId: '',
        product: {
            title: '',
            description: '',
            price: '',
            originalPrice: '',
            category: '',
            condition: '',
            images: [],
            status: '在售'
        },
        errors: {},
        loading: true,
        submitting: false,
        showCategoryPicker: false,
        categoryOptions: [
            '电子产品', '书籍', '服装', '日用品', '美妆', '运动户外',
            '家具家电', '票务', '食品', '其他'
        ]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.id) {
            this.setData({ productId: options.id });
            this.fetchProductDetails(options.id);
        } else {
            wx.navigateBack();
            Toast.fail('缺少商品ID');
        }
    },

    /**
     * 获取商品详情
     */
    async fetchProductDetails(id) {
        try {
            this.setData({ loading: true });

            const response = await new Promise((resolve, reject) => {
                wx.request({
                    url: `${app.globalData.baseUrl}/api/products/${id}`,
                    method: 'GET',
                    header: {
                        'Authorization': `Bearer ${wx.getStorageSync('token')}`
                    },
                    success: resolve,
                    fail: reject
                });
            });

            if (response.data.success) {
                const product = response.data.data.product;

                // 检查是否是当前用户的商品
                const userInfo = wx.getStorageSync('userInfo');
                if (product.seller._id !== userInfo._id) {
                    wx.navigateBack();
                    Toast.fail('无权编辑该商品');
                    return;
                }

                this.setData({
                    product,
                    loading: false
                });

                // 如果已售出，提示无法修改
                if (product.status === '已售出') {
                    Toast('已售出的商品不能修改');
                    setTimeout(() => {
                        wx.navigateBack();
                    }, 1500);
                }
            } else {
                Toast.fail('获取商品详情失败');
                this.setData({ loading: false });
            }
        } catch (error) {
            console.error('获取商品详情失败:', error);
            Toast.fail('获取商品详情失败');
            this.setData({ loading: false });
        }
    },

    // 表单字段变更处理
    onTitleChange(e) {
        this.setData({
            'product.title': e.detail,
            'errors.title': e.detail ? '' : '请输入商品标题'
        });
    },

    onPriceChange(e) {
        this.setData({
            'product.price': e.detail,
            'errors.price': e.detail ? '' : '请输入售价'
        });
    },

    onOriginalPriceChange(e) {
        this.setData({
            'product.originalPrice': e.detail
        });
    },

    onConditionChange(e) {
        this.setData({
            'product.condition': e.detail,
            'errors.condition': e.detail ? '' : '请输入商品成色'
        });
    },

    onDescriptionChange(e) {
        this.setData({
            'product.description': e.detail,
            'errors.description': e.detail ? '' : '请输入商品描述'
        });
    },

    // 分类选择器相关方法
    showCategoryPicker() {
        this.setData({ showCategoryPicker: true });
    },

    onCategoryPickerClose() {
        this.setData({ showCategoryPicker: false });
    },

    onCategoryConfirm(e) {
        this.setData({
            'product.category': e.detail.value,
            'errors.category': '',
            showCategoryPicker: false
        });
    },

    // 状态选择相关方法
    onStatusChange(e) {
        this.setData({
            'product.status': e.detail
        });
    },

    onStatusCellClick(e) {
        const { name } = e.currentTarget.dataset;
        this.setData({
            'product.status': name
        });
    },

    // 图片处理相关方法
    async chooseImage() {
        try {
            const res = await wx.chooseMedia({
                count: 9 - this.data.product.images.length,
                mediaType: ['image'],
                sourceType: ['album', 'camera'],
                sizeType: ['compressed']
            });

            if (res.tempFiles.length > 0) {
                const uploadTasks = res.tempFiles.map(file => this.uploadImage(file.tempFilePath));
                const uploadedImages = await Promise.all(uploadTasks);

                this.setData({
                    'product.images': [...this.data.product.images, ...uploadedImages],
                    'errors.images': ''
                });
            }
        } catch (error) {
            console.error('选择图片失败:', error);
        }
    },

    async uploadImage(filePath) {
        // 这里应该是上传到云存储的逻辑
        // 简化起见，这里直接返回临时路径
        // 实际应用中应该替换为真正的云存储上传逻辑
        return filePath;
    },

    deleteImage(e) {
        const { index } = e.currentTarget.dataset;
        const images = [...this.data.product.images];
        images.splice(index, 1);

        this.setData({
            'product.images': images
        });
    },

    previewImage(e) {
        const { index } = e.currentTarget.dataset;
        wx.previewImage({
            current: this.data.product.images[index],
            urls: this.data.product.images
        });
    },

    // 表单验证
    validateForm() {
        const { product } = this.data;
        const errors = {};

        if (!product.title.trim()) {
            errors.title = '请输入商品标题';
        }

        if (!product.price) {
            errors.price = '请输入售价';
        } else if (isNaN(product.price) || Number(product.price) <= 0) {
            errors.price = '请输入有效的售价';
        }

        if (product.originalPrice && (isNaN(product.originalPrice) || Number(product.originalPrice) <= 0)) {
            errors.originalPrice = '请输入有效的原价';
        }

        if (!product.condition.trim()) {
            errors.condition = '请输入商品成色';
        }

        if (!product.category) {
            errors.category = '请选择商品分类';
        }

        if (!product.description.trim()) {
            errors.description = '请输入商品描述';
        }

        if (product.images.length === 0) {
            errors.images = '请上传至少一张商品图片';
        }

        this.setData({ errors });
        return Object.keys(errors).length === 0;
    },

    // 提交表单
    async submitForm() {
        if (!this.validateForm()) {
            Toast.fail('请完善商品信息');
            return;
        }

        this.setData({ submitting: true });

        try {
            const { product, productId } = this.data;

            // 构造要发送的数据对象
            const updateData = {
                title: product.title.trim(),
                description: product.description.trim(),
                price: Number(product.price),
                originalPrice: product.originalPrice ? Number(product.originalPrice) : product.price,
                category: product.category,
                condition: product.condition.trim(),
                images: product.images,
                status: product.status
            };

            const response = await new Promise((resolve, reject) => {
                wx.request({
                    url: `${app.globalData.baseUrl}/api/products/${productId}`,
                    method: 'PUT',
                    data: updateData,
                    header: {
                        'Authorization': `Bearer ${wx.getStorageSync('token')}`,
                        'Content-Type': 'application/json'
                    },
                    success: resolve,
                    fail: reject
                });
            });

            if (response.data.success) {
                Toast.success('保存成功');
                setTimeout(() => {
                    wx.navigateBack();
                }, 1500);
            } else {
                Toast.fail(response.data.message || '保存失败');
            }
        } catch (error) {
            console.error('更新商品失败:', error);
            Toast.fail('更新失败，请重试');
        } finally {
            this.setData({ submitting: false });
        }
    }
}) 